package com.yc.videoview;

import ohos.agp.components.Component;
import ohos.agp.components.StackLayout;
import ohos.multimodalinput.event.TouchEvent;

/**
 * <pre>
 *     @author yangchong
 *     blog  : https://github.com/yangchong211
 *     time  : 2018/8/29
 *     desc  : 小窗口触摸移动
 *     revise:
 * </pre>
 */
public class SmallWindowTouch implements Component.TouchEventListener {
    private int mDownX, mDownY;
    private int mMarginLeft, mMarginTop;
    private int _xDelta, _yDelta;
    private Component mView;

    public SmallWindowTouch(Component view, int marginLeft, int marginTop) {
        super();
        mMarginLeft = marginLeft;
        mMarginTop = marginTop;
        mView = view;
    }

    @Override
    public boolean onTouchEvent(Component component, TouchEvent touchEvent) {
        // MmiPoint mt = touchEvent.getPointerPosition(0); 获取屏幕的xy
        final int X = (int) touchEvent.getPointerScreenPosition(0).getX();
        final int Y = (int) touchEvent.getPointerScreenPosition(0).getY();
        switch (touchEvent.getAction()) { // & MotionEvent.ACTION_MASK
            case TouchEvent.PRIMARY_POINT_DOWN:
                mDownX = X;
                mDownY = Y;

                StackLayout.LayoutConfig lParams = (StackLayout.LayoutConfig) mView.getLayoutConfig();
                _xDelta = X - lParams.getMarginLeft();
                _yDelta = Y - lParams.getMarginTop();
                break;
            case TouchEvent.CANCEL:
                if (Math.abs(mDownY - Y) < 5 && Math.abs(mDownX - X) < 5) {
                    return false;
                } else {
                    return true;
                }

            case TouchEvent.PRIMARY_POINT_UP:
                StackLayout.LayoutConfig layoutParams = (StackLayout.LayoutConfig) mView.getLayoutConfig();
                layoutParams.setMarginLeft(X - _xDelta);
                layoutParams.setMarginTop(Y - _yDelta);
                if (layoutParams.getMarginLeft() >= mMarginLeft) {
                    layoutParams.setMarginLeft(mMarginLeft);
                }

                if (layoutParams.getMarginTop() >= mMarginTop) {
                    layoutParams.setMarginTop(mMarginTop);
                }

                if (layoutParams.getMarginLeft() <= 0) {
                    layoutParams.setMarginLeft(0);
                }

                if (layoutParams.getMarginTop() <= 0) {
                    layoutParams.setMarginTop(0);
                }
                mView.setLayoutConfig(layoutParams);
                break;
            default:
                break;
        }
        return false;
    }
}